package com.echo.util;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class TestExcel {

	private static String EXCEL_HSSF_CONTENT_TYPE = "application/vnd.ms-excel";

	private static String EXCEL_HSSF_HEADER = "Content-disposition";

	private static String EXCEL_HSSF_ATTACHMENT = "attachment;filename=";

	private static String EXCEL_HSSF_PREFIX = ".xls";

	public void excle(HttpServletResponse response, String fileName, List<String> headList, List<List> dataList)
			throws IOException {

		HSSFWorkbook workbook = new HSSFWorkbook();// 第一步,创建一个webbook,对应一个excel文件
		HSSFSheet sheet = workbook.createSheet();// 第二步,在webbook中添加

		HSSFCellStyle headStyle = workbook.createCellStyle();
		headStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);// 设置头的样式为居中

		HSSFCellStyle dataStyle = workbook.createCellStyle();
		dataStyle.setAlignment(HSSFCellStyle.ALIGN_LEFT);

		int headrowstart = 0;

		HSSFRow headrow = sheet.createRow(headrowstart);// 第三步，在sheet中添加表头第0行,注意老版本poi对Excel的行数列数有限制short

		for (int i = 0; i < headList.size(); i++) {
			HSSFCell cell = headrow.createCell(i);
			cell.setCellStyle(headStyle);
			cell.setCellValue(headList.get(i));

		}
		int datarowstart = 1;

		for (List list : dataList) {
			HSSFRow datarow = sheet.createRow(datarowstart);
			for (int i = 0; i < list.size(); i++) {
				HSSFCell cell = datarow.createCell(i);
				cell.setCellStyle(dataStyle);
				cell.setCellValue((String) list.get(i));
			}
			datarowstart++;
		}
		response.setContentType(EXCEL_HSSF_CONTENT_TYPE);
		response.setHeader(EXCEL_HSSF_HEADER, EXCEL_HSSF_ATTACHMENT + fileName + EXCEL_HSSF_PREFIX);

		OutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			workbook.write(outputStream);
			outputStream.flush();

		} catch (IOException e) {
			e.printStackTrace();
			throw e;
		} finally {
			if (outputStream != null)
				outputStream.close();
		}

	}

}
